#include "maker_base.h"
// uint8_t tap1[] = {0x2a, 0xab, 0x43, 0xf6, 0x03, 0xb4};
// uint8_t tap0[] = {0xbe, 0x26, 0x55, 0xa5, 0xce, 0x34};
int main()
{
    int send_log_count = 0;
    int recv_log_count = 0;
    // 打开tap1网卡接口

    char tap_name[] = "tap1";
    int fd = open("/dev/net/tun", O_RDWR);
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(struct ifreq));
    strncpy(ifr.ifr_ifrn.ifrn_name, tap_name, sizeof(tap_name));
    ifr.ifr_ifru.ifru_flags = IFF_TAP | IFF_NO_PI;
    if (ioctl(fd, TUNSETIFF, &ifr) != 0)
    {
        perror(strerror(errno));
        exit(errno);
    };

    pid_t child = fork();
    if (child == 0)
    {
        while (1)
        {
            sleep(1);
            /* code */
            int max_pck_size = 1500 + sizeof(struct ether_header);
            unsigned char buf[1500 + sizeof(struct ether_header)] = {0};
            int read_count = read(fd, buf, max_pck_size);
            DEBUG_PRINT("recv_log %d: read pck read_count:%d", recv_log_count, read_count);
            DEBUG_PRINT("recv_log %d: type: %02x%02x", recv_log_count, buf[12], buf[13]);
            if (buf[12] == 0x08 && buf[13] == 0x06)
            {
                DEBUG_PRINT("recv_log %d: pck is arp", recv_log_count);
            }
            recv_log_count++;
        }
    }
    else if (child > 0)
    {
        DEBUG_PRINT("child pid is %d", child);

        // uint8_t sender_hw_a[6] = {0x2a, 0xab, 0x43, 0xf6, 0x03, 0xb4};
        // 这个地址不属于任何一个interface mac地址 随便给的
        uint8_t sender_hw_a[6] = {0x2a, 0xab, 0x43, 0xf6, 0x03, 0x77};
        uint8_t target_hw_a[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
        uint8_t sender_p_a[4] = {192, 168, 2, 252};
        uint8_t target_p_a[4] = {192, 168, 2, 1};

        struct arp_pck pck = arp_maker(sender_hw_a, sender_p_a, target_hw_a, target_p_a);
        while (1)
        {
            /* code */
            int write_count = write(fd, &pck, sizeof(struct arp_pck));
            DEBUG_PRINT("sender_log %d: sizeof(struct arp_pck) %zd", send_log_count, sizeof(struct arp_pck));
            DEBUG_PRINT("sender_log %d: write_count %d", send_log_count, write_count);
            send_log_count++;
            sleep(1);
        }
    }
}